const Router = require('koa-router');
const fs = require('await-fs');
const path = require('path');
const common = require('../../lib/common');

let router = new Router();

// 渲染登陆
router.get('/login',async ctx=>{
    await ctx.render('admin/login',{
        errmsg:ctx.query.errmsg || '',
        HTTP_ROOT:ctx.HTTP_ROOT
    });
})

function findAdmin(adminList,username){
    let a = null;
    adminList.forEach(element => {
        if(element.username==username){
            a=element;
        }
    });
    return a;
}
// 请求登陆
router.post('/login',async ctx=>{
    const {HTTP_ROOT,ADMIN_PREFIX} = ctx.config;
    let {username,password} = ctx.request.fields;
    // 读取本地文件 
    let admins = JSON.parse((await fs.readFile(
        path.resolve(__dirname,'../../admins.json')
    )).toString());
    if(!findAdmin(admins,username)){
        // 如果用户名不存在 重定向回去
        ctx.redirect(`${HTTP_ROOT}/admin/login?errmsg=${encodeURIComponent('用户名不存在')}`);
    }else{
        if(findAdmin(admins,username).password!=common.md5(password+ADMIN_PREFIX)){
            // 如果密码错误重定向回去
            ctx.redirect(`${HTTP_ROOT}/admin/login?errmsg=${encodeURIComponent('密码错误')}`);
        }else{
            ctx.session['admin']=username;
            ctx.redirect(`${HTTP_ROOT}/admin/banner`);
        }
    }
})

// 控制权限
router.all('*',async (ctx,next)=>{
    const {HTTP_ROOT} = ctx.config;
    if(ctx.session['admin']){
        await next();
    }else{
        ctx.redirect(`${HTTP_ROOT}/admin/login`)
    }
})

// 
router.get('/banner',async ctx=>{
    const {HTTP_ROOT} = ctx.config;
    let datas= await ctx.db.query('SELECT * FROM banner_table');
    await ctx.render('admin/table',{
        HTTP_ROOT:ctx.HTTP_ROOT,
        type:'view',
        datas:datas,
        fields:[
            {title:'标题',name:'title',type:'text'},
            {title:'图片',name:'src',type:'file'},
            {title:'链接',name:'href',type:'text'},
            {title:'序号',name:'serial',type:'number'},
        ]
    })
})

// 提交banner
router.post('/banner',async ctx=>{
    const {HTTP_ROOT} = ctx.config;
    let {title,src,href,serial} = ctx.request.fields;
    // 获取真正的文件名 
    src = path.basename(src[0].path);
    await ctx.db.query('INSERT INTO banner_table (title,src,href,serial) VALUES (?,?,?,?)',[
        title,src,href,serial
    ])
    ctx.redirect(`${HTTP_ROOT}/admin/banner`);
}) 
// 删除
router.get('/banner/delete/:id',async ctx=>{
    let {id} = ctx.params;
    let {UPLOAD_DIR,HTTP_ROOT} = ctx.config;

    let datas= await ctx.db.query('SELECT * FROM banner_table WHERE ID=?',[id]);
    if(datas.length==0){
        ctx.body = 'no data';
    }else{
        let row = datas[0];
        await common.unlink(path.resolve(UPLOAD_DIR,row.src));
        await ctx.db.query('DELETE FROM banner_table WHERE ID=?',[id]);
        ctx.redirect(`${HTTP_ROOT}/admin/banner`);
    }
}) 

// 修改渲染页面
/*router.get('/banner/modify/:id',async ctx=>{
    let {id} = ctx.params;
    let {UPLOAD_DIR,HTTP_ROOT} = ctx.config;

    let datas= await ctx.db.query('SELECT * FROM banner_table WHERE ID=?',[id]);
    // 如果没有数据 则走下面的方法
    ctx.assert(datas.length,400,'no data');
    // 此时已经确定有数据了
    let row = datas[0];
    
    await ctx.render('admin/table',{
        HTTP_ROOT,
        type:'modify',
        old_data:row,
        fields:[
            {title:'标题',name:'title',type:'text'},
            {title:'图片',name:'src',type:'file'},
            {title:'链接',name:'href',type:'text'},
            {title:'序号',name:'serial',type:'number'},
        ],
        action:`${HTTP_ROOT}/admin/modify/${id}`,
    })
})*/
// 修改渲染页面 API
router.get('/banner/get/:id',async ctx=>{
    let {id} = ctx.params;
    // 记得判断id  要不前端随便写会报错

    let data = await ctx.db.query('SELECT * FROM banner_table WHERE ID=?',[id]);
    if(data.length==0){
        ctx.body={
            err:1,
            msg:'no this data'
        };
    }else{
        ctx.body={
            err:0,
            msg:'success',
            data:data[0]
        }
    }




})
// 执行修改操作
router.post('/banner/modify/:id',async ctx=>{
    let post =ctx.request.fields;
    let {id} = ctx.params;
    let {UPLOAD_DIR,HTTP_ROOT} = ctx.config;

    // 获取原来的数据 用来删除原来的图片
    let old_data =await ctx.db.query('SELECT * FROM banner_table');
    // 如果没有原始数据则表示有问题 返回400
    ctx.assert(old_data.length , 400 , 'no this data');
    
    let old_data_src = old_data[0].src;
    let keys = ['title','href','serial'];
    let vals=[];
    keys.forEach(key=>{
        vals.push(post[key]);
    })

    let src_change = false;
    // 单独处理上传的文件
    if(post.src && post.src.length && post.src[0].size){
        keys.push('src');
        vals.push(path.basename(post.src[0].path));
        src_change=true;
    }
    await ctx.db.query(`UPDATE banner_table SET ${
        keys.map(key=>`${key}=?`).join(',')
    } WHERE ID=?`,[...vals,id]);

    // 删除原来的图片
    if(src_change){
        await common.unlink(path.resolve(UPLOAD_DIR,old_data_src));
    }

    ctx.redirect(`${HTTP_ROOT}/admin/banner`);
})  
module.exports = router.routes();